package edu.gyc.data.struct.stack;

import java.util.Scanner;

public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(4);
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        char key = ' ';
        while (loop) {
            System.out.println("s(show):显示Stack");
            System.out.println("e(exit):退出程序");
            System.out.println("a(add):添加数据到Stack");
            System.out.println("g(get):从Stack取数据");
            System.out.println("p(peek):查看Stack头数据");
            System.out.println("n(num):查看Stack有几个数据");
            key = scanner.next().charAt(0);//取第一个字符
            switch (key) {
                case 's':
                    arrayStack.show();
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    System.out.println("程序退出。");
                    System.exit(0);
                    break;
                case 'a':
                    System.out.println("请输入一个整数：");
                    int n = scanner.nextInt();
                    arrayStack.push(n);
                    break;

                case 'g':
                    try {
                        int t = arrayStack.pop();
                        System.out.println("取出的数据是：" + t);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'p':
                    try {
                        int d = arrayStack.peek();
                        System.out.println("栈顶数据是：" + d);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;


            }
        }
    }
}
class ArrayStack {
    private int maxSize;
    private int[] stack;
    private int top=-1;

    public ArrayStack(int maxSize) {
        this.maxSize=maxSize;
        stack = new int[this.maxSize];
    }

    //栈满
    public boolean isFull() {
        return top==maxSize-1;
    }

    public boolean isEmpty() {
        return top==-1;
    }

    public void push(int n) {
        if (isFull()) {
            System.out.println("栈满了，无法加入数据");
            return;
        }
        top++;
        stack[top]=n;
    }

    public int pop() {
        if (isEmpty()) {
            throw  new RuntimeException("栈空，无数据可弹出");
        }
        int t=stack[top];
        top--;
        return t;
    }

    public void show() {
        if (isEmpty()) {

            System.out.println("栈空，无数据可显示");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n",i,stack[i]);
        }
    }
    public int peek() {
        if (isEmpty()) {
            throw  new RuntimeException("栈空，无数据可弹出");
        }
        return stack[top];
    }

}

